package user_api

import (
	"benkendSystem/database"
	"benkendSystem/models"
	"benkendSystem/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

// 更新用户信息

func UpdateUser(c *gin.Context) {
	in := new(UpdateUserRequest)
	err := c.ShouldBindJSON(in)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	// 校验用户名是否符合规则
	if utils.ValidateUsername(in.UserName) == false {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户名必须是3到20的字母或数字",
		})
		return
	}
	// 修改用户数据
	err = database.DB.Model(new(models.User)).Where("id = ?", in.ID).Updates(map[string]any{
		"username":      in.UserName,
		"realname":      in.RealName,
		"phone_number":  in.PhoneNumber,
		"enable_flag":   in.EnableFlag,
		"role_id":       in.RoleId,
		"department_id": in.DepartmentID,
	}).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "操作成功",
	})
}
